import { createStore } from 'vuex';
import storage from '../utils/storage';
import mutations from './mutations.js';
import { topCategory } from '@/api/constants';
import { getNewCartGoods, mergeCart, findCart, deleteCart, updateCart, insertCart, checkAllCart } from '@/api/cart'
// 创建一个新的 store 实例
const state = {
  userInfo: storage.getItem('userInfo') || {}, // 获取用户信息
  cart: storage.getItem('cart') || {},
  category: storage.getItem('category') || {
    list: topCategory.map((item) => ({
      name: item,
    })),
  },
  list: storage.getItem('list') || [],
};

export default createStore({
  state,
  mutations,
  getters: {
    // 有效商品列表
    validList(state) {
      return state.list.filter((goods) => goods.stock > 0 && goods.isEffective);
    },
    // 有效商品件数
    validTotal(state, getters) {
      return getters.validList.reduce((p, c) => p + c.count, 0);
    },
    // 有效商品总金额
    validAmount(state, getters) {
      return (
        getters.validList.reduce((p, c) => p + c.nowPrice * 100 * c.count, 0) /
        100
      );
    },
    // 无效商品列表
    invalidList(state) {
      return state.list.filter(item => !(item.stock > 0 && item.isEffective))
    },
    // 选中商品列表
    selectedList(state, getters) {
      return getters.validList.filter(item => item.selected)
    },
    // 选中商品件数
    selectedTotal(state, getters) {
      return getters.selectedList.reduce((p, c) => p + c.count, 0)
    },
    // 选中商品总金额
    selectedAmount(state, getters) {
      return getters.selectedList.reduce((p, c) => p + (c.nowPrice * 100 * c.count), 0) / 100
    },
    // 是否全选
    isCheckAll(state, getters) {
      return getters.validList.length === getters.selectedList.length && getters.selectedList.length !== 0
    }
  },
  actions: {
    // 修改规格
    updateCartSku(ctx, { oldSkuId, newSku }) {
      return new Promise((resolve, reject) => {
        if (ctx.state.userInfo.token) {
          // 已登陆
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          deleteCart([oldSkuId]).then(() => {
            return insertCart({ skuId: newSku.skuId, count: oldGoods.count })
          }).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCartList', data)
            resolve()
          })

        } else {
          // 未登录
          const oldGoods = ctx.state.list.find(item => item.skuId === oldSkuId)
          ctx.commit('deleteCart', oldSkuId)
          const { skuId, price: nowPrice, spacsText: attrsText, oldPrice: price, inventory: stock } = newSku
          const newGoods = { ...oldGoods, skuId, nowPrice, attrsText, price, stock }
          ctx.commit('insertCart', newGoods)
          resolve();
        }
      });
    },
    // 合并购物车
    async mergeCart(ctx) {
      const cartList = ctx.state.list.map(goods => {
        return {
          skuId: goods.skuId,
          selected: goods.selected,
          count: goods.count,
        }
      })
      await mergeCart(cartList)
      ctx.commit('setCart', [])
    },

    // 单条删除购物车数据
    deleteCart(ctx, payload) {
      return new Promise((resolve, reject) => {
        if (ctx.state.userInfo.token) {
          // 已登陆
          deleteCart([payload]).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCartList', data)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('deleteCart', payload);
          resolve();
        }
      });
    },
    // 加入购物车
    insertCart(ctx, payload) {
      return new Promise((resolve, reject) => {
        if (ctx.state.userInfo.token) {
          // 已登陆
          insertCart({ skuId: payload.skuId, count: payload.count }).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCartList', data)
            resolve()
          })
        } else {
          // 未登录
          ctx.commit('insertCart', payload);
          resolve();
        }
      });
    },

    // 获取商品列表
    findCart(ctx) {
      return new Promise((resolve, reject) => {
        if (ctx.state.userInfo.token) {
          // 已登陆
          findCart().then(res => {
            ctx.commit('setCartList', res)
            resolve()
          })
        } else {
          // 未登录
          const promiseArr = ctx.state.list.map(goods => {
            return getNewCartGoods(goods.skuId)
          })
          Promise.all(promiseArr).then(results => {
            results.forEach((data, i) => {

              ctx.commit('updateCart', { skuId: ctx.state.list[i].skuId, data })
            })
            // 更新本地购物车
            resolve()
          })
        }
      })
    },
    // 修改购物车
    updateCart(ctx, payload) {
      // 修改需要 skuId && selected || count
      const isAll = ctx.getters.isCheckAll
      return new Promise((resolve, reject) => {
        if (ctx.state.userInfo.token) {
          // 登录
          updateCart(payload).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCartList', data)
            resolve(isAll)
          })
        } else {
          // 未登录
          ctx.commit('updateCart', payload);
          resolve(isAll);
        }
      });
    },
    // 全选商品列表
    selectedCartAll(ctx) {
      const isAll = ctx.getters.isCheckAll
      const cartList = ctx.getters.validList
      return new Promise((resolve, reject) => {
        if (ctx.state.userInfo.token) {
          // 登录
          ctx.commit('selectedCartAll', { cartList, isAll: !isAll });
          resolve(!isAll);
          const ids = cartList.map(item => item.skuId)
          checkAllCart({ selected: !isAll, ids }).then(async () => {
            return await findCart()
          }).then(res => {
            ctx.commit('setCartList', res)
            resolve(!isAll)
          })

        } else {
          // 未登录
          ctx.commit('selectedCartAll', { cartList, isAll: !isAll });
          resolve(!isAll);
        }
      });
    },
    // 删除选中商品
    deleteSelCart(ctx, isClear) {
      const cartList = isClear ? ctx.getters.invalidList : ctx.getters.validList
      return new Promise((resolve, reject) => {
        if (ctx.state.userInfo.token) {
          // 登录
          const ids = []
          cartList.forEach(element => {
            if (element.selected === true) {
              ids.push(element.skuId)
            }
          });
          deleteCart(ids).then(() => {
            return findCart()
          }).then(data => {
            ctx.commit('setCartList', data)
            resolve()
          })
        } else {
          // 未登录
          cartList.forEach(element => {
            if (element.selected === true) {
              ctx.commit('deleteCart', element.skuId)
            }
          });
          resolve();
        }
      });
    }
  },
});
